package com.zyg.util;

import com.zyg.model.BaseTreeModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 生成树形返回值
 * @param <T>
 */

@Component
public class TreeBuildUtil<T extends BaseTreeModel> {

    public List<T> treeBuilder(List<T> allTreeInfo){
        return treeBuilderParent(allTreeInfo);
    }

    private List<T> treeBuilderParent(List<T> allTreeInfo){

        List<T> treeNodeParent = new ArrayList<>();
        //获取一级权限
        for(T treeNode : allTreeInfo){
            if(StringUtils.isBlank(treeNode.getParentId())){
                treeNodeParent.add(treeNode);
            }
        }

        //获取二级子节点
        for(T treeNode : treeNodeParent){
            List<T> childTree = treeBuilderChild(treeNode.getId(),allTreeInfo);
            treeNode.setChildren(childTree);
        }

        return treeNodeParent;
    }

    private List<T> treeBuilderChild(String parentId,List<T> allTreeList){

        //子菜单列表
        List<T> treeNodeChildList = new ArrayList<>();
        for (T treeNode : allTreeList) {
            if(parentId.equals(treeNode.getParentId())) {
                treeNodeChildList.add(treeNode);
            }
        }

        //遍历 获取子菜单的子菜单
        for (T treeNode : treeNodeChildList) {
            List<T> child = treeBuilderChild(treeNode.getId(),allTreeList);
            treeNode.setChildren(child);
        }

        //递归出口  childList长度为0
        if (treeNodeChildList.size() == 0) {
            return new ArrayList<>();
        }

        return treeNodeChildList;
    }

}
